import 'dart:math';

import 'package:auto_route/annotations.dart';
import 'package:base/common/chat_ui/chat.dart';
import 'package:flutter/material.dart';

import '../../common/chat_core/chat_controller/in_memory_chat_controller.dart';
import '../../common/chat_core/models/builders.dart';
import '../../common/chat_core/models/message.dart';
import '../../common/chat_core/models/user.dart';
import '../../common/chat_ui/composer.dart';
import '../../common/chat_ui/utils/composer_action.dart';
import '../../common/chat_ui/utils/typedefs.dart';
import '../../common/net/user_req.dart';

@RoutePage()
class Tab1Page extends StatefulWidget {
  const Tab1Page({super.key});

  @override
  State<Tab1Page> createState() => _Tab1PageState();
}

class _Tab1PageState extends State<Tab1Page> {
  final _chatController = InMemoryChatController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Chat(
        currentUserId: "userId",
        builders: Builders(
          loadMoreBuilder: (context) => const Center(
            child: CircularProgressIndicator(),
          ),
          // 自定义输入框
          composerBuilder: (context) => Composer(
            bottomWidget: Container(
              height: 200,
              color: Colors.green,
              width: double.infinity,
            ),
            leftActions: [
              ComposerAction(
                icon: Icon(Icons.photo),
                type: ComposerActionType.panel,
                onTap: () {
                  print("photo");
                },
              ),
              ComposerAction(
                icon: Icon(Icons.emoji_emotions),
                onTap: () {
                  print("handleEmoji");
                  _chatController.scrollToIndex(0);
                },
              ),
            ],
            rightActions: const [
              ComposerAction(
                icon: Icon(Icons.send_rounded),
                type: ComposerActionType.send,
              ),
            ],
          ),
        ),
        resolveUser: (id) async {
          print("resolveUser id: $id");
          return User(id: id, name: 'John Doe');
        },
        chatController: _chatController,
        onMessageSend: (text) {
          _chatController.insertMessage(
            TextMessage(
              // Better to use UUID or similar for the ID - IDs must be unique
              id: '${DateTime.now().microsecondsSinceEpoch}',
              authorId: 'userId',
              createdAt: DateTime.now().toUtc(),
              text: text,
            ),
          );
        },
        onEndReached: () async {
          // 模拟加载历史消息
          final history = List.generate(10, (index) {
            final messageId = '${index + _chatController.messages.length}';
            return TextMessage(
              id: messageId,
              text: '历史消息 $messageId',
              authorId: index % 2 == 0 ? 'user2' : 'userId',
              createdAt: DateTime.now().subtract(Duration(minutes: index + 1)),
            );
          });
          await Future.delayed(Duration(seconds: 2));
          // 将历史消息插入到顶部
          int count = _chatController.messages.length;
           _chatController.insertAllMessages(history, index:0);
          _chatController.scrollToMessage(history.last.id);
        },
      ),
    );
  }

  @override
  void dispose() {
    print("Tab1Page dispose");
    _chatController.dispose();
    super.dispose();
  }
}
